<?php
plugin('admin-top-edit-and-delete-pages');
if(($_POST['save'] || $_GET['id']) && !$admin->canDo('Edit Page'))
	$admin->noAccess('Edit Page');
if($_POST['deleteid'] && !$admin->canDo('Delete Page')) {
	echo $admin->noAccess('Delete Page', true);
	exit();
}
if(file_exists(BASE_URL.'includes/admin/editors/fckeditor/fckeditor.php')) {
	include(BASE_URL.'includes/admin/editors/fckeditor/fckeditor.php');
	$rte = true;
}
else {
	$rte = false;
}
if($_GET['serialize']) {
	$queryBuild = removeBlanks(explode('|', $_POST['order']));
	foreach($queryBuild as $value) {
		list($parent_id, $this_id, $weight) = explode(':', $value);
		$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET orderingid = '{$weight}', parent_id = '{$parent_id}' WHERE id = '{$this_id}' LIMIT 1";
		$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', $admin->db->error()));
	}
	echo $admin->message('success', 'Menu Reordered!', 'Check your site! It was updated at '.date('g:i:s').'!');
	exit();
}
$id = sanitize_sql_string($_GET['id']);
if($_POST['deleteid']) {
	$did = $_POST['deleteid'];
	$id = end(explode('-', $did));
	$sql = "DELETE FROM ".DBTABLEPREFIX."content_pages WHERE id = '{$id}' LIMIT 1";
	$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', $admin->db->error()));
	if(!$query) {
		echo $admin->message('error', 'Unknown Error', 'See above.');
	}
	else {
		echo $admin->message('success', 'Page Deleted', "Let's hope that wasn't an accident!");
	}
	exit();
}
if($_POST['save']) {
	$list = $theme->buildNavArray();
	$secondary_list = $theme->arraySecondaryNavigation();
	foreach($_POST as $key => $value) {
		$_POST[$key] = sanitize_sql_string($value);
	}
	$error = "";
	if($_POST['page-title'] == "") {
		$error[] = "Don't leave the page title blank!";
	}
	if($_POST['menu-title'] == "") {
		$error[] = "Don't leave the menu title blank!";
	}
	$time = time();
	$sql        = "SELECT id, menutitle FROM ".DBTABLEPREFIX."content_pages";
	$query      = $admin->db_query($sql) or die($admin->db->error());
	while($result     = $admin->db->fetchAssoc()) {
		$menuitems[$admin->make_clean_url($result['menutitle'])] = $result['id'];
	}
	if(array_key_exists($admin->make_clean_url($_POST['menu-title']), $menuitems)) {
		if($menuitems[$admin->make_clean_url($_POST['menu-title'])] != $_POST['id'])
			$error[] = "Page with that name already exists!";
	}
	if($error == "") {
		$parent = explode('-', $_POST['parent-item']);
		$parent_cat = $parent[0];
		$parent_id = $parent[1];
		if($_POST['showInMenu'] == 'show') {
			$arr = serialize(array('show' => $_POST['showInMenu']));
			$checked = 'checked="checked" ';
		}
		else {
			$arr = 'a:1:{s:4:"show";s:6:"hidden";}';
		}
		if($parent_cat == "p") {
			$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET title = '".$_POST['page-title']."', content = '".$_POST['content']."', menutitle = '".$_POST['menu-title']."',
			parent_id = '".$parent_id."', orderingid = '".$_POST['weight']."', time = '$time', secondary = '', options = '$arr' WHERE id = '$id'";
		}
		elseif ($parent_cat == "s") {
			$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET title = '".$_POST['page-title']."', content = '".$_POST['content']."', menutitle = '".$_POST['menu-title']."',
			parent_id = '".$parent_id."', orderingid = '".$_POST['weight']."', time = '$time', secondary = 'yes', options = '$arr' WHERE id = '$id'";
		}
		$content = $admin->db_query($sql) or die($admin->db->error());
		if($content) {
			$output .= $admin->message("success","Woohoo! Your Page \"".stripslashes(stripslashes(stripslashes($_POST['page-title'])))."\" was updated!", "It will show up as \"".stripslashes(stripslashes(stripslashes($_POST['menu-title'])))."\" in the menu.");
		}
	}
	if($error !== "") {
		$list_errors = "<ul class='error-list'>";
		foreach($error as $key => $value) {
			$list_errors .= "<li>".$value."</li>";
		}
		$list_errors .= "</ul>";
		$output .= $admin->message("error", "Oops! We encountered ".count($error)." error(s) when trying to add the page.", $list_errors);
	}
		$parent = explode('-', $_POST['parent-item']);
		$parent_cat = $parent[0];
		$parent_id = $parent[1];
		if($_POST['showInMenu'] == 'show') {
			$checked = 'checked="checked" ';
		}
	$options = "<option value='0'>None (Root Item)</option>";
	$list = $theme->buildNavArray();
	for($col = -20; $col <= 20; $col++) {
		$weight .= "\t<option value='$col'";
		if($col == $_POST['weight']) {
			$weight .= " selected='selected'";
		}
		$weight .= ">$col</option>\n";
	}
	if($rte == true) {
		$FCKeditor_content = new FCKeditor('content') ;
		$FCKeditor_content->BasePath = THEME_URL.'includes/admin/editors/fckeditor/';
		$FCKeditor_content->Value = stripslashes(stripslashes(stripslashes($_POST['content'])));
		$FCKeditor_content->Width = '100%' ;
		$FCKeditor_content->Height = '350' ;
		$textarea = $FCKeditor_content->CreateHtml();
	}
	else {
		$textarea = '<textarea name="content" id="editContent" rows="20" cols="50">'.stripslashes(stripslashes(stripslashes($_POST['content']))).'</textarea>';
	}
			$main = $theme->optionListFromArray($list, "p-", $parent_id);
			$seco = $theme->optionListFromArray($secondary_list, "s-", $parent_id);
			if($row['secondary'] == 'yes') {
				if(substr_count('selected=', $seco) > 0) {
					$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
				}
				else {
					$seco = '<option value="s-0" selected="selected">None (Secondary Menu Root Item)</option>'.$seco;
				}
			}
			else {
				if(substr_count('selected=', $main) > 0) {
					$main = '<option value="p-0">None (Root Item)</option>'.$main;
				}
				else {
					$main = '<option value="p-0" selected="selected">None (Main Menu Root Item)</option>'.$main;
				}
				$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
			}

$form = '
						<form action="" method="post" class="niceform">
							<fieldset>
								<h2>Edit Page "'.stripslashes(stripslashes(stripslashes($_POST['page-title']))).'"</h2>
								<div class="form-row">
									<label for="page-title" class="page-title">Page Title:</label><span><input type="text" class="page-title" name="page-title" value="'.stripslashes(stripslashes(stripslashes($_POST['page-title']))).'" /></span>
								</div>
								<div class="form-row">
									<label for="menu-title">Menu Title:<span class="small gray">This is what will show up in the menu.</span></label><span><input type="text" name="menu-title" value="'.stripslashes(stripslashes(stripslashes($_POST['menu-title']))).'" /></span>
								</div>
								<div class="form-row">
									<label for="parent-item">Parent Item</label>
									<span>
										<select name="parent-item">
											<optgroup label="Main Menu">
												'.$main.'
											</optgroup>
											<optgroup label="Secondary Optional Menu">
												'.$seco.'
											</optgroup>
										</select>
										<input type="checkbox" name="showInMenu" value="show" '.$checked.'/><span class="pad">Show in menu?</span>
									</span>
								</div>
									<div class="form-row">
										<label for="weight">Weight <a href="javascript:;" class="helplink" title="<strong style=\'font-size:16px;display:block;\'>Weight</strong>Weight Allows you to manage how items are ordered.<br />For example: If you weight this page 12 and another page 11, in the menu the other page would show before this one.">[Help]</a></label>
										<span>
											<select name="weight">
											'.$weight.'
											</select>
										</span>
									</div>
								<div class="form-row">
									<label class="content" for="content">Content</label>
									<span class="content">
										'.stripslashes(stripslashes(stripslashes($textarea))).'
									</span>
								</div>
								<div class="form-row form-row-last">
									<label for="save">Save</label>
									<span>
										<input type="hidden" name="id" value="'.$_POST['id'].'" class="hidden" />
										<input type="submit" name="save" value="Update Page" class="submit" />
									</span>
								</div>
							</fieldset>
						</form>
	';
	$output .= $form;
}
elseif (isset($_GET['id'])) {
	$list = $theme->buildNavArray();
	$secondary_list = $theme->arraySecondaryNavigation();
	$list = $theme->buildNavArray();
	$sql = "SELECT * FROM ".DBTABLEPREFIX."content_pages WHERE id = $id LIMIT 1";
	$content = $admin->db_query($sql) or die($admin->db->error());
	$count = $admin->db->numRows($content);
	if($count == "1") {
		$row = $admin->db->fetchArray($content);
			$options = unserialize($row['options']);
			if($options['show'] == 'show')
				$checked = 'checked="checked" ';
			for($col = -20; $col <= 20; $col++) {
				$weight .= "\t<option value='$col'";
				if($col == $row['orderingid']) {
					$weight .= " selected='selected'";
				}
				$weight .= ">$col</option>\n";
			}
			foreach($row as $key => $value) {
				$row[$key] = stripslashes(stripslashes(stripslashes($value)));
			}
			if($rte == true && $admin->getSetting('FCKeditor (WYSIWYG Editor)') == 'Enabled') {
				$FCKeditor_content = new FCKeditor('content') ;
				$FCKeditor_content->BasePath = THEME_URL.'includes/admin/editors/fckeditor/';
				$FCKeditor_content->Config['ProtectedSource.Add'] = '/<\?[\s\S]*?\?>/g';
				$FCKeditor_content->Value = stripslashes(stripslashes(stripslashes($row['content'])));
				$FCKeditor_content->Width = '100%' ;
				$FCKeditor_content->Height = '350' ;
				$textarea = $FCKeditor_content->CreateHtml();
			}
			else {
				$textarea = '<textarea name="content" id="editContent" rows="20" cols="50">'.stripslashes(stripslashes(stripslashes($row['content']))).'</textarea>';
			}
			$main = $theme->optionListFromArray($list, "p-", $row['parent_id']);
			$seco = $theme->optionListFromArray($secondary_list, "s-", $row['parent_id']);
			if($row['secondary'] == 'yes') {
				if(substr_count('selected=', $seco) > 0) {
					$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
				}
				else {
					$seco = '<option value="s-0" selected="selected">None (Secondary Menu Root Item)</option>'.$seco;
				}
			}
			else {
				if(substr_count('selected=', $main) > 0) {
					$main = '<option value="p-0">None (Root Item)</option>'.$main;
				}
				else {
					$main = '<option value="p-0" selected="selected">None (Main Menu Root Item)</option>'.$main;
				}
				$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
			}
		$form = '
							<form action="" method="post">
								<fieldset>
									<h2>Edit Page "'.$row['title'].'"</h2>
									<div class="form-row">
										<label for="page-title" class="page-title">Page Title:</label><span><input type="text" class="page-title" name="page-title" value="'.$row['title'].'" /></span>
									</div>
									<div class="form-row">
										<label for="menu-title">Menu Title:<span class="small gray">This is what will show up in the menu.</span></label><span><input type="text" name="menu-title" value="'.$row['menutitle'].'" /></span>
									</div>
									<div class="form-row">
										<label for="parent-item">Parent Item</label>
										<span>
											<select name="parent-item">
												<optgroup label="Main Menu">
													'.$main.'
												</optgroup>
												<optgroup label="Secondary Optional Menu">
													'.$seco.'
												</optgroup>
											</select>
											<input type="checkbox" name="showInMenu" value="show" '.$checked.'/><span class="pad">Show in menu?</span>
										</span>
									</div>
									<div class="form-row">
										<label for="weight">Weight <a href="javascript:;" class="helplink" title="<strong style=\'font-size:16px;display:block;\'>Weight</strong>Weight Allows you to manage how items are ordered.<br />For example: If you weight this page 12 and another page 11, in the menu the other page would show before this one.">[Help]</a></label>
										<span>
											<select name="weight">
											'.$weight.'
											</select>
										</span>
									</div>
									<div class="form-row">
										<label class="content" for="content">Content</label>
										<span class="content">
											'.$textarea.'
										</span>
									</div>
									<div class="form-row form-row-last">
										<label for="save">Save</label>
										<span>
											<input type="hidden" name="id" value="'.$row['id'].'" class="hidden" />
											<input type="submit" name="save" value="Update Page" class="submit" />
										</span>
									</div>
								</fieldset>
							</form>
		';
	}
	else {
		
	}
	$output .= $form;
}
else {
	$THEME_URL=THEME_URL;
	$after = '	</fieldset></form>';
	$output .= <<<EOT
	<script type='text/javascript' src='{$THEME_URL}includes/admin/js/jTree.js'></script>
	<script type='text/javascript'>
	$(document).ready(function() {
		$('#rearrangeButton').toggle(function () {
			$('#list-pages .rearrange-page').css('visibility','visible');
			$('#list-pages').jTree();
			$(this).text('Save');
		},function () {
			$('#list-pages .rearrange-page').css('visibility','hidden');
			var serialStr = "";
			var order = "";
			$("#list-pages li").each(function(){			
				parentId = $(this).parent("ul").parent("li").attr("id");
				if (parentId == undefined) parentId = "0";
				order = $(this).prevAll("li").size()+1; 
				if ( parentId != "root") serialStr += ""+parentId+":"+$(this).attr("id")+":"+order+"|";
			});
			$(this).text('Saving...');
			$.ajax({
				type: 'POST',
				url: '?page=edit-and-delete-pages&serialize=true',
				data: 'order='+serialStr,
				success: function(responseText) {
					$('#rearrangeButton').text('Rearrange Pages');
					$('body').append("<div class='floating-box'>"+responseText+"</div>");
					$('.floating-box').hide().fadeIn('slow').animate({opacity: 1}, 3000).fadeOut('slow');
					addClose();
			}
			});
		});	
		$('#secondaryRearrangeButton').toggle(function () {
			$('#list-pages2 .rearrange-page').css('visibility','visible');
			$('#list-pages2').jTree();
			$(this).text('Save');
		},function () {
			$('#list-pages2 .rearrange-page').css('visibility','hidden');
			var serialStr = "";
			var order = "";
			$("#list-pages2 li").each(function(){			
				parentId = $(this).parent("ul").parent("li").attr("id");
				if (parentId == undefined) parentId = "0";
				order = $(this).prevAll("li").size()+1; 
				if ( parentId != "root") serialStr += ""+parentId+":"+$(this).attr("id")+":"+order+"|";
			});
			$(this).text('Saving...');
			$.ajax({
				type: 'POST',
				url: '?page=edit-and-delete-pages&serialize=true',
				data: 'order='+serialStr,
				success: function(responseText) {
					$('#secondaryRearrangeButton').text('Rearrange Secondary Pages');
					$('body').append("<div class='floating-box'>"+responseText+"</div>");
					$('.floating-box').hide().fadeIn('slow').animate({opacity: 1}, 3000).fadeOut('slow');
					addClose();
			}
			});
		});	
		$('.secondary-list-pages .admin-edit-link').each(function () {
			var id = $(this).attr('id');
			$(this).attr('id', 's-'+id);
		});
	});
	</script>
	<form action='' method='get'>
	<fieldset>
		<h2>Edit, Delete and Rearrange Pages</h2>
		<p class='pageDesc'><strong>To delete a page:</strong> click the red 'X' to the far left of the page you wish to delete.<br />
		<strong>To edit a page:</strong> click the white sheet of paper to the far left of the page you wish to edit.<br/>
		<strong>To rearrange pages:</strong> click the Rearrange button to the far right and then click and drag items into place.
		<br/>The partial transparent pages are hidden pages.</p>
	<br />
	<div class='response'></div>
	<h3><button class='button' id='rearrangeButton'>Rearrange Main Pages</button> Main Menu Items</h3>
	<div class='left disable-warnings' style='top:0;margin-bottom:10px;padding-left:59px;'>If a parent item is deleted, <strong>ALL SUB-PAGES WILL BE DELETED!</strong></div>\n
EOT;
$output .= $admin->adminPublicPageList("list-pages' class='primary-list-pages", "list-page-sub", "selected", true, "edit-and-delete-pages", false, $theme->arrayNavigation(true)).
	'<br class="clear" /><h3><button class="button" id="secondaryRearrangeButton">Rearrange Secondary Pages</button> Secondary Menu Items</h3>'.
	$admin->adminPublicPageList("list-pages2' class='secondary-list-pages", "list-page-sub", "selected", true, "edit-and-delete-pages", false, $theme->arraySecondaryNavigation(true));
}
$admin->page_info['content']['page_title'] = "Edit a Page";
$admin->page_info['content']['page_content']	= $output.$after;
plugin('admin-bottom-edit-and-delete-pages');
//Display page
include(BASE_URL.'includes/admin/admin.php');
?>